package form

import (
	"errors"
	"fmt"
	"strings"
	"yunj/pkg/global"
	"yunj/pkg/yunj/app/model"
	"yunj/pkg/yunj/core/builder/builderdto"
	"yunj/pkg/yunj/util"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type index struct {
}

var Index *index

func DropdownSearchOptions(ctx *gin.Context) (options []builderdto.Option, err error) {
	param := util.QueryParams(ctx)
	query := global.MySQL.Model(&model.DemoUser{}).Offset(0).Limit(5).Select("id,name").Order("id desc")
	if values, exists := param["values"]; exists {
		if values, ok := values.(string); ok && values != "" {
			query = query.Where("id in(?)", strings.Split(values, ","))
		}
	}
	if keywords, exists := param["keywords"]; exists {
		if keywords, ok := keywords.(string); ok && keywords != "" {
			query = query.Where("name like ?", "%"+keywords+"%")
		}
	}
	var users []model.DemoUser
	queryErr := query.Find(&users).Error
	if queryErr != nil && !errors.Is(queryErr, gorm.ErrRecordNotFound) {
		err = fmt.Errorf("数据查询异常！%v", queryErr)
		return
	}
	options = make([]builderdto.Option, 0, len(users))
	for _, user := range users {
		options = append(options, builderdto.Option{Value: user.Id, Label: user.Name})
	}
	return
}
